package com.nut.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nut.article.cache.CacheInMap;
import com.nut.article.common.Result;
import com.nut.article.entity.Category;
import com.nut.article.mapper.CategoryMapper;
import com.nut.article.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CacheInMap cacheInMap;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result<List<Category>> list() {
        Object cache = cacheInMap.findCache(categoryList, () -> {
            return categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getPid, 0).orderByAsc(Category::getSort));
        }, 1, TimeUnit.HOURS);

        return Result.ok((List<Category>) cache);
    }

    @Override
    public Result cleanCache() {
        cacheInMap.removeKey(categoryList);
        return Result.ok();
    }

    @Override
    public Result<Category> getById(Serializable id) {
        Category category = categoryMapper.selectById(id);
        return Result.ok(category);
    }

    @Override
    public Result add(Category category) {
        categoryMapper.insert(category);
        cacheInMap.removeKey(categoryList);
        return Result.ok();
    }

    @Override
    public Result updateById(Category category) {
        categoryMapper.updateById(category);
        cacheInMap.removeKey(categoryList);
        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        for (Integer id : ids) {
            categoryMapper.deleteById(id);
        }
        cacheInMap.removeKey(categoryList);
        return Result.ok();
    }

}
